/*
 * Created on 2005-2-17
 *
 */
package bma.common.langutil.core;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 关中
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class NameValue<V> extends ObjectPair<V, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3833748772134924341L;

	public NameValue() {
		super();
	}

	public NameValue(String key, V value) {
		super(value, key);
	}

	/**
	 * @return Returns the name.
	 */
	public String getName() {
		return getAttribute();
	}

	/**
	 * @param name
	 *            The name to set.
	 */
	public void setName(String name) {
		setAttribute(name);
	}

	public boolean same(String name) {
		return sameAttribute(name);
	}

	public boolean sameIgnoreCase(String name) {
		if (name == null) {
			return this.getName() == null;
		}
		return name.equalsIgnoreCase(this.getName());
	}

	public static <E> List<String> toNameList(List<NameValue<E>> list) {
		List<String> result = new LinkedList<String>();
		for (NameValue<E> nv : list) {
			result.add(nv.getName());
		}
		return result;
	}

	public static <E> List<E> toValueList(List<NameValue<E>> list) {
		List<E> result = new LinkedList<E>();
		for (NameValue<E> nv : list) {
			result.add(nv.getValue());
		}
		return result;
	}

	public static <E> E get(List<NameValue<E>> list, String key) {

		for (NameValue<E> nv : list) {
			if (nv.same(key)) {
				return nv.getValue();
			}
		}

		return null;
	}

	public static <E> void put(List<NameValue<E>> list, String key, E value) {
		for (NameValue<E> nv : list) {
			if (nv.same(key)) {
				nv.setValue(value);
			}
		}

		NameValue<E> nv = new NameValue<E>(key, value);
		list.add(nv);
	}

	public static <E> boolean remove(List<NameValue<E>> list, String key,
			boolean removeAll) {
		boolean r = false;
		Iterator<NameValue<E>> it = list.iterator();
		while (it.hasNext()) {
			if (it.next().same(key)) {
				it.remove();
				r = true;
				if (!removeAll) {
					break;
				}
			}
		}
		return r;
	}

}